package day07;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import untils.LoginEvent;

import java.util.List;
import java.util.Map;

/**
 * 使用cep检测连续三次登陆失败
 */
public class Example1 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<LoginEvent> stream = env
                .fromElements(
                        new LoginEvent("user-1", "fail", 1000L),
                        new LoginEvent("user-1", "fail", 2000L),
                        new LoginEvent("user-2", "success", 3000L),
                        new LoginEvent("user-1", "fail", 4000L),
                        new LoginEvent("user-1", "fail", 5000L)
                )
                .assignTimestampsAndWatermarks(WatermarkStrategy.<LoginEvent>forMonotonousTimestamps()
                        .withTimestampAssigner(new SerializableTimestampAssigner<LoginEvent>() {
                            @Override
                            public long extractTimestamp(LoginEvent element, long recordTimestamp) {
                                return element.ts;
                            }
                        }));

        // 定义模板：连续三次登录失败
        Pattern<LoginEvent, LoginEvent> pattern = Pattern
                .<LoginEvent>begin("first")
                .where(new SimpleCondition<LoginEvent>() {
                    @Override
                    public boolean filter(LoginEvent value) throws Exception {
                        return value.type.equals("fail");
                    }
                })
                .next("second") // 紧跟在first后面
                .where(new SimpleCondition<LoginEvent>() {
                    @Override
                    public boolean filter(LoginEvent value) throws Exception {
                        return value.type.equals("fail");
                    }
                })
                .next("third")
                .where(new SimpleCondition<LoginEvent>() {
                    @Override
                    public boolean filter(LoginEvent value) throws Exception {
                        return value.type.equals("fail");
                    }
                });

        // 在流上匹配模板
        PatternStream<LoginEvent> patternStream = CEP.pattern(stream.keyBy(r -> r.userId), pattern);

        // 取出匹配到的结果
        patternStream
                .select(new PatternSelectFunction<LoginEvent, String>() {
                    // {
                    //   "first": [LoginEvent],
                    //   "second": [LoginEvent],
                    //   "third": [LoginEvent]
                    // }
                    @Override
                    public String select(Map<String, List<LoginEvent>> pattern) throws Exception {
                        LoginEvent first = pattern.get("first").get(0);
                        LoginEvent second = pattern.get("second").get(0);
                        LoginEvent third = pattern.get("third").get(0);
                        return "用户" + first.userId + "在时间戳：" + first.ts + ";" + second.ts + ";" + third.ts + "" +
                                "连续三次登录失败。";
                    }
                })
                .print();

        env.execute();
    }
}
